package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.service.AnalysisWebsiteParamManageService;
import com.hunttown.mes.manage.service.IotMessageManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.IotMessageDTO;
import com.hunttown.mes.rpc.domain.query.IotMessageDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2020-11-20 11:14:58
 */
@Controller
@RequestMapping(value = "/basic/message-msg")
public class MessageMsgController {

    private final static Logger logger = LoggerFactory.getLogger(MessageMsgController.class);

    private final IotMessageManageService iotMessageService;
    private final AnalysisManageManageService manageService;
    private final ModelService modelService;
    private final AnalysisWebsiteParamManageService websiteService;

    @Autowired
    public MessageMsgController(IotMessageManageService iotMessageService, AnalysisManageManageService manageService, ModelService modelService, AnalysisWebsiteParamManageService websiteService) {
        this.iotMessageService = iotMessageService;
        this.manageService = manageService;
        this.modelService = modelService;
        this.websiteService = websiteService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, IotMessageDTOQuery dtoQuery) {
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        //只查询自己的信息
        //系统中存储的是会员ID
        dtoQuery.setReceiveId(modelService.getUserIdByAdminId(curr_obj.getId()));
        dtoQuery.setMsType(1);
        dtoQuery.setOrderBy("order by id desc");
        Page<IotMessageDTO> dataPage = iotMessageService.getForPage(dtoQuery);

        for (IotMessageDTO item : dataPage.getItems()) {
            if (item.getSendId() == 0) {
                item.setSendName("系统信息");
            } else {
                item.setSendName(modelService.getUserTrueName(item.getSendId()));
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        return "basic/message-msg/index";
    }

    //详情
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(HttpServletRequest request, Model model, Integer id) {
        if (id == null || id <= 0) {
            throw new RuntimeException("未查询到消息记录");
        }

        IotMessageDTO obj = iotMessageService.getById(id);
        if (obj.getSendId() == 0) {
            obj.setSendName("系统信息");
        } else {
            obj.setSendName(modelService.getUserTrueName(obj.getSendId()));
        }
        model.addAttribute("Obj", obj);

        //更新为已读
        IotMessageDTO update = new IotMessageDTO();
        update.setId(obj.getId());
        update.setIsRead(1);
        update.setReadTime(new Date());
        iotMessageService.updateInfoById(update);

        //版权信息
        String pin = AdminBaseClass.getPin(request);
        model.addAttribute("copyright", websiteService.getWebsiteCopyrightFromCache(request, pin));

        return "basic/message-msg/detail";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = (id == null ? 0 : id);

        IotMessageDTO obj;

        if (id > 0) {
            obj = iotMessageService.getById(id);
        } else {
            obj = new IotMessageDTO();
            obj.setId(0);
        }
        model.addAttribute("Obj", obj);

        return "basic/message-msg/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, IotMessageDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO = iotMessageService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = iotMessageService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = iotMessageService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = iotMessageService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        IotMessageDTO obj = new IotMessageDTO();
        obj.setId(id);

        if (id > 0) {
            obj = iotMessageService.getById(id);
        }
        iotMessageService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

    //region Ajax异步获取个人消息
    @RequestMapping(value = "/getPersonMessage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getPersonMessage(Integer userId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (userId == null || userId <= 0) {
            return map;
        }

        //系统中存储的是会员ID
        IotMessageDTOQuery dtoQuery = new IotMessageDTOQuery();
        dtoQuery.setReceiveId(userId);
        dtoQuery.setMsType(1);
        dtoQuery.setIsRead(0);
        dtoQuery.setPageSize(6);
        dtoQuery.setOrderBy("order by id desc");
        Page<IotMessageDTO> dataPage = iotMessageService.getForPage(dtoQuery);

        List<Map<String, String>> datamap = new ArrayList<>();

        for (IotMessageDTO item : dataPage.getItems()) {
            Map<String, String> data = new HashMap<>();
            data.put("id", item.getId() + "");
            data.put("title", item.getMsTitle());
            data.put("date", item.getSendTimeSr());
            datamap.add(data);
        }

        map.put("datamap", datamap);
        map.put("size", dataPage.getTotalItems());
        map.put("returnCode", 1);

        return map;
    }
    //endregion
}